/*
 * log.c
 *
 *  Created on: 2012-8-6
 *      Author: wx
 */
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <sys/time.h>
#include <stdarg.h>

#include "log.h"

//获取当前系统时间字符串，日志文件名格式 yyyy-MM-dd HH:mm:ss.uuuuuuu
//返回指针为静态指针，不能释放。
static const char * GetLogTime();

//日志文件句柄
static FILE * m_fpLog;


//初始化日志文件
int InitLog(const char * logfile)
{
	//if ((m_fpLog = fopen("/var/log/apnsserver.log", "a")) == NULL)
	if ((m_fpLog = fopen(logfile, "a")) == NULL)
	{
		perror("Open log file");
		return -1;
	} else	return 0;
}

//发送日志
void SendLog(const char * sLog, ...)
{
	static int iCount;
	static char buf[1024];
	iCount = sprintf(buf, "%s - ", GetLogTime());

	static va_list arg_ptr;
	va_start(arg_ptr, sLog);
	iCount = iCount + vsprintf(buf + iCount, sLog, arg_ptr);
	va_end(arg_ptr);

	iCount = iCount + sprintf(buf+iCount, "\n");

printf("%s", buf);

	if ((int) fwrite(buf, iCount, 1, m_fpLog) != 1)
	{
		printf("Write log data error! Exit!\n");
		exit(1);
	}
	if (fflush(m_fpLog))
	{
		printf("Flush log file error! Exit!\n");
		exit(1);
	}
}

//获取当前系统时间字符串，日志文件名格式 yyyy-MM-dd HH:mm:ss.uuuuuuu
//返回指针为静态指针，不能释放。
const char * GetLogTime()
{
	static char sTime[32];
	static char buf[32];
	static time_t curtime;
	struct tm * loctime;

	curtime = time(NULL);
	loctime = localtime(&curtime);
	strftime(buf, 32, "%Y-%m-%d %H:%M:%S.", loctime);

	static struct timeval *tv;
	static struct timezone *tz;
	tv = malloc(sizeof(struct timeval));
	tz = malloc(sizeof(struct timezone));
	gettimeofday(tv, tz);

	sprintf(sTime, "%s%06d", buf, (int) tv->tv_usec);

	free(tv);
	free(tz);

	return sTime;
}
